﻿using MarkDownFileSplitter.Meilisearch.Control;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MarkDownFileSplitter.Meilisearch
{
    [ToolboxItem(false)]
    public partial class MeilisearchTabControl : UserControl
    {
        private ContextMenuStrip indexContextMenu;
        private ContextMenuStrip emptyAreaContextMenu;
        private ImageList m_treeImageList;
        private SearchTestControl m_searchControl;

        public MeilisearchTabControl()
        {
            InitializeComponent();

            // 初始化节点右键菜单
            indexContextMenu = new ContextMenuStrip();
            indexContextMenu.Items.Add("新增Index", null, OnAddIndexClick);
            indexContextMenu.Items.Add("补充Document", null, OnAddDocumentClick);
            indexContextMenu.Items.Add("清空Document", null, OnClearDocumentsClick);
            indexContextMenu.Items.Add("删除", null, OnDeleteIndexClick);

            // 初始化空白区域右键菜单
            emptyAreaContextMenu = new ContextMenuStrip();
            emptyAreaContextMenu.Items.Add("新增Index", null, OnAddIndexClick);

            // 为TreeView添加右键菜单事件
            treeView_indexes.NodeMouseClick += TreeView_indexes_NodeMouseClick;
            // 为TreeView添加空白区域右键菜单事件
            treeView_indexes.MouseUp += TreeView_indexes_EmptyAreaMouseUp;
            // 添加节点选择事件
            treeView_indexes.AfterSelect += TreeView_indexes_AfterSelect;


            m_treeImageList = new ImageList();
            m_treeImageList.Images.Add(MarkDownFileSplitter.Properties.Resources.document);
            m_treeImageList.Images.Add(MarkDownFileSplitter.Properties.Resources.folderOpen);
            treeView_indexes.ImageList=m_treeImageList;

            this.addDocumentControl1.IsNewIndex = false;

            IndexTreeView.SetInstance(this.treeView_indexes);

            this.filterSettingControl1.Dock = DockStyle.Fill;

            m_searchControl = new SearchTestControl();
            m_searchControl.Dock= DockStyle.Fill;
            this.tabPage5.Controls.Add(m_searchControl);
        }

        private async Task Reset()
        {
            this.treeView_indexes.Nodes.Clear();
            var result = await MeilisearchUploader.Instance.QueryIndexes();
            if (result == null)
            {
                MessageBox.Show("查询失败，请检查Meilisearch配置的Url和ApiKey");
                return;
            }

            // 从JObject中提取索引信息
            var indexes = result["results"].Select(x => new IndexInfo(x["uid"].ToString(), x["primaryKey"].ToString()));

            foreach (IndexInfo index in indexes)
            {
                var node = new TreeNode(index.IndexName);
                node.Tag = index;
                node.SelectedImageIndex = 1;
                node.ImageIndex = 0;
                this.treeView_indexes.Nodes.Add(node);
            }
        }

        private async void MeilisearchTabControl_Load(object sender, EventArgs e)
        {
            await Reset();
        }

        private void TreeView_indexes_NodeMouseClick(object? sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeView_indexes.SelectedNode = e.Node;
                indexContextMenu.Show(treeView_indexes, e.Location);
            }
        }
        private void TreeView_indexes_EmptyAreaMouseUp(object? sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && treeView_indexes.GetNodeAt(e.Location) == null)
            {
                emptyAreaContextMenu.Show(treeView_indexes, e.Location);
            }
        }

        private async void TreeView_indexes_AfterSelect(object? sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                // 获取选中节点的索引信息
                var indexInfo = e.Node.Tag as IndexInfo;

                //修改界面文字
                this.label_selectedIndex.Text = this.label_selectedIndex.Text.Substring(0, this.label_selectedIndex.Text.IndexOf("：") + 1) + indexInfo.IndexName;
                this.label_selectedPrimaryKey.Text = this.label_selectedPrimaryKey.Text.Substring(0, this.label_selectedPrimaryKey.Text.IndexOf("：") + 1) + indexInfo.PrimaryKey;

                //更新数据预览页
                this.indexViewerControl1.RefreshGrid(indexInfo.IndexName, indexInfo);
                //更新新增Document页
                List<string> attributeNames = await MeilisearchUploader.Instance.GetDocumentAttributeNames(indexInfo.IndexName);//获取已入库数据的字段，避免前后入库数据不一致
                this.addDocumentControl1.SetIndexSetting(indexInfo.IndexName, indexInfo.PrimaryKey, attributeNames);
                //更新字段过滤管理Tab
                this.filterSettingControl1.CurrentIndexUid = indexInfo.IndexName;
                this.filterSettingControl1.RefreshGridAsync(attributeNames);
                //更新TaskTab页
                this.taskManagerControl1.RefreshGrid(indexInfo.IndexName);
                this.fieldEditControl1.UpdateIndex(indexInfo);
                //更新搜索页
                m_searchControl.UpdateIndex(indexInfo);
            }
        }

        private void OnAddIndexClick(object? sender, EventArgs e)
        {
            FormIndexCreaterByDocument form = new FormIndexCreaterByDocument() { StartPosition = FormStartPosition.CenterParent };
            form.ShowDialog();
        }

        private async void OnClearDocumentsClick(object? sender, EventArgs e)
        {
            var selectedNode = treeView_indexes.SelectedNode;
            if (selectedNode != null)
            {
                string indexName = selectedNode.Text;
                var result = MessageBox.Show($"确定要清空{indexName}中的Document吗？此操作不可逆！", "清空确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    await MeilisearchUploader.Instance.ClearDocuments(indexName);
                }
            }
        }

        private async void OnDeleteIndexClick(object? sender, EventArgs e)
        {
            var selectedNode = treeView_indexes.SelectedNode;
            if (selectedNode != null)
            {
                string indexName = selectedNode.Text;
                var result = MessageBox.Show($"确定要删除名为{indexName}的Index吗？此操作不可逆！", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    treeView_indexes.Nodes.Remove(selectedNode);
                    await MeilisearchUploader.Instance.DeleteIndex(indexName);
                }
            }
        }

        private void OnAddDocumentClick(object? sender, EventArgs e)
        {
            var selectedNode = treeView_indexes.SelectedNode;
            if (selectedNode != null)
            {
                var indexInfo = selectedNode.Tag as IndexInfo;
                if (indexInfo != null)
                {
                    FormIndexCreaterByDocument form = new FormIndexCreaterByDocument() 
                    { 
                        StartPosition = FormStartPosition.CenterParent 
                    };
                    
                    // 设置为补充模式，并预设索引信息
                    form.SetAddDocumentMode(indexInfo.IndexName, indexInfo.PrimaryKey);
                    
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        // 刷新当前选中的索引信息
                        TreeView_indexes_AfterSelect(null, new TreeViewEventArgs(selectedNode, TreeViewAction.ByMouse));
                    }
                }
            }
        }

        private void toolStripButton_meilisearchSetting_Click(object sender, EventArgs e)
        {
            FormSetting_Meilisearch formSetting = new FormSetting_Meilisearch(Reset) { StartPosition = FormStartPosition.CenterParent };
            formSetting.ShowDialog();
        }

        private void toolStripButton_createIndex_Click(object sender, EventArgs e)
        {
            FormIndexCreaterByDocument form = new FormIndexCreaterByDocument() { StartPosition = FormStartPosition.CenterParent };
            form.ShowDialog();
        }
    }
}
